// import dayjs from "dayjs";
import { TaskGetPage, TaskSave, TaskDelete } from "@/api/teacher/task";
import { GetAllPlan } from "@/api/teacher/plan";
import { GetSelectItemBySelectType } from "@/api/teacher/common";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, nextTick } from "vue";
import { ElMessage, FormInstance } from "element-plus";

export function usePlan() {
  const STaskList = reactive({
    planId: null,
    moduleId: null
  });
  // 任务设置
  const form = reactive({
    id: 0, //自增 0
    planId: 0, // 计划ID
    moduleId: "", // 模块名称的  ‘A’ 'B'
    taskName: "", // 任务名称
    markId: 0, // 默认 0
    remark: "", // 任务说明
    Important: "", //重要提示
    scores: 0, // 默认
    createTime: "", // 默认
    status: "", // 默认
    createUser: "" // 默认
  });

  const dataList = ref<any>([]);
  const planList = ref<any>([]);
  const SelectItemList = ref<any>([]);
  const loading = ref(false);
  const addPanelVisible = ref(false);
  const updatePanelVisible = ref(false);
  const loadingTitle = ref(undefined);
  const propsDetails = ref();
  const rules = {
    moduleId: [
      {
        required: true,
        message: "请选择模块名称！",
        trigger: ["blur", "change"]
      }
    ],
    taskName: [
      {
        required: true,
        message: "请输入任务名称！",
        trigger: ["blur", "change"]
      }
    ],
    remark: [
      {
        required: true,
        message: "请填写任务说明",
        trigger: ["blur", "change"]
      }
    ]
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      prop: "Id",
      minWidth: 100
    },
    {
      label: "模块名称",
      prop: "SelectName",
      minWidth: 200
    },
    {
      label: "任务名称",
      prop: "TaskName",
      minWidth: 200
    },
    {
      label: "分值",
      prop: "Import",
      minWidth: 80
    },
    {
      label: "任务说明",
      prop: "Remark",
      minWidth: 180,
      cellRenderer: () => <span>点击修改查看内容详情</span>
    },
    {
      label: "重要提示",
      prop: "Important",
      minWidth: 180,
      cellRenderer: () => <span>点击修改查看内容详情</span>
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  function handleUpdate(row: any | undefined) {
    if (!STaskList.planId) {
      ElMessage.warning("请选择计划名称！");
      return;
    }
    if (row) {
      loadingTitle.value = "修改计划";
      nextTick(() => {
        form.id = row.Id; //自增 0
        form.planId = row.planId; // 计划ID
        form.moduleId = row.ModuleId; // 模块名称的  ‘A’ 'B'
        form.taskName = row.TaskName; // 任务名称
        form.markId = row.MarkId; // 默认 0
        form.remark = row.Remark; // 任务说明
        form.Important = row.Important || "？"; //重要提示
        form.scores = row.Score; // 默认
        form.createTime = row.CreateTime; // 默认
        form.status = row.Status; // 默认
        form.createUser = row.CreateUser; // 默认
      });
    } else {
      form.id = 0;
      form.planId = STaskList.planId; // 计划ID
      loadingTitle.value = "添加计划";
    }
    updatePanelVisible.value = true;
  }

  async function handleDelete(row) {
    const respone = await TaskDelete(row);
    ElMessage({
      message: respone.msg,
      type: "success"
    });
    onSearch();
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  // 查看详情
  function ViewDetails(row: object) {
    propsDetails.value = row;
  }

  async function onSearch() {
    loading.value = true;
    const row = {
      pageindex: pagination.currentPage,
      pagesize: pagination.pageSize,
      ...STaskList
    };
    try {
      const { data } = await TaskGetPage(row);
      dataList.value = data?.list;
      propsDetails.value = "";
      loading.value = false;
    } catch (error) {
      setTimeout(() => {
        loading.value = false;
      }, 3000);
    }
  }

  //添加计划
  const addPlan = (addDtoRef: FormInstance | undefined) => {
    (addDtoRef as any).validate(async valid => {
      if (!valid) return;
      const respone = await TaskSave(form);
      if (respone.status === 200) {
        ElMessage({
          message: respone.msg,
          type: "success"
        });
        ClosePanelVisible(addDtoRef);
        onSearch();
      } else {
        ElMessage({
          message: respone.msg,
          type: "error"
        });
      }
    });
  };

  async function updatePlan() {
    const respone = await TaskSave(form);
    if (respone.success) {
      onSearch();
      updatePanelVisible.value = false;
      ElMessage({
        message: respone.msg,
        type: "success"
      });
    }
  }

  // 獲取計劃名稱
  async function GetAllPlans() {
    const respone = await GetAllPlan();
    if (respone.success) {
      planList.value = respone.data;
    }
  }

  //  获取模块列表
  async function GetSelectItemBySelectTypes() {
    const respone = await GetSelectItemBySelectType("MKMC");
    if (respone.success) {
      SelectItemList.value = respone.data;
    }
  }

  // async function SearcTaskList() {
  //   loading.value = true;
  //   const data = {STaskList.planId};
  //   const data = await GetPage(planId);
  //   console.log("002", data);
  // }
  // 关闭
  function ClosePanelVisible(row: FormInstance | undefined) {
    updatePanelVisible.value = false;
    row.resetFields();
  }

  const resetForm = formEl => {
    formEl.resetFields();
    updatePanelVisible.value = false;
  };

  onMounted(() => {
    // onSearch();
    GetAllPlans();
    GetSelectItemBySelectTypes();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    planList,
    STaskList,
    propsDetails,
    pagination,
    loadingTitle,
    SelectItemList,
    addPanelVisible,
    updatePanelVisible,
    rules,
    onSearch,
    ViewDetails,
    resetForm,
    handleUpdate,
    handleDelete,
    // SearcTaskList,
    handleSizeChange,
    ClosePanelVisible,
    handleCurrentChange,
    handleSelectionChange,
    addPlan,
    updatePlan
  };
}
